<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <div>
    <!-- class="title1" -->
    <div class="lg:flex !mt-4">
      <div class="lg:w-7/10 enter-y !mr-4">
        <BasicTable @register="registerTable" @edit-change="rowChange">
          <template #tableTitle>
            <div style="display: flex; align-items: center">
              <Icon :icon="getTitle.icon" class="m-1 pr-1" />
              <span class="mr-2"> 备货区 </span>
            </div>
          </template>
          <template #toolbar>
            <a-button type="default" @click="handleInventory()">
              <!-- <EyeOutlined /> -->
              <Icon icon="i-ant-design:eye-outlined" /> {{ t('库存展望查询') }}
            </a-button>
          </template>
          <template #fdate="{ record }">
            {{ record.fdate?.substring(0, 10) }}
          </template>
          <template #firstColumn="{ record }">
            <a @click="handleViewForm({ id: record.hid })">
              {{ record.fbillno }}
            </a>
          </template>
          <template #combinedProducts="{ record }">
            <div v-html="handlecombinedProducts(record.combinedProducts)"> </div>
          </template>
        </BasicTable>
      </div>
      <div class="lg:w-3/10 enter-y">
        <!-- <div style="background: #fff"> -->
        <BasicTable @register="registerTable3">
          <template #tableTitle>
            <Icon :icon="getTitle.icon" class="m-1 pr-1" />
            <span> 拣货区</span>
            <!-- <span class="ml-2" style="font-weight: bold; color: red"
                >【说明：备货区记录仅24小时内有效；失效后将会自动清空】</span
              > -->
          </template>
          <template #combinedProducts="{ record }">
            <div v-html="handlecombinedProducts(record.combinedProducts)"> </div>
          </template>
          <template #toolbar>
            <Dropdown placement="bottom" :trigger="['click']">
              <a-button type="error" ghost @click.prevent v-auth="'jh:plan:jhPlanArea:edit'">
                <Icon icon="ant-design:delete-outlined" /> {{ t('清除备货区') }}
              </a-button>
              <template #overlay>
                <Menu>
                  <MenuItem @click="handlegx" v-if="hasPermission(['jh:plan:jhPlanArea:edit'])">
                    <span>勾选记录清除</span>
                  </MenuItem>
                  <MenuDivider />
                  <MenuDivider />
                  <MenuItem @click="handlebr" v-if="hasPermission(['jh:plan:jhPlanArea:edit'])">
                    <span>本人数据清除</span>
                  </MenuItem>
                  <MenuDivider />
                </Menu>
              </template>
            </Dropdown>
            <a-button
              type="success"
              ghost
              v-auth="'jh:plan:jhPlanArea:edit'"
              @click="handleCreateJhBill"
            >
              <Icon icon="i-ant-design:check-outlined" /> {{ t('生成拣货单') }}
            </a-button>
          </template>
        </BasicTable>
        <!-- </div> -->
      </div>

      <BasicModal v-bind="$attrs" @register="registerModal" title="请确认拣货方式" @ok="handleQr">
        <BasicForm @register="registerForm" />
      </BasicModal>
      <tzList @register="registerDrawer" />
      <invList @register="registerDrawerInv" />
      <!-- @success="handleSuccess"  -->
      <InputFormView @register="registerViewDrawer" />
    </div>
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsWmsRdRd32Rdrecord32JhList',
    components: { Menu, Dropdown, MenuItem: Menu.Item, MenuDivider: Menu.Divider },
  });
</script>
<script lang="ts" setup>
  import { unref, onMounted, computed, ref, defineComponent } from 'vue';
  import {
    TreeSelect,
    Menu,
    Dropdown,
    TableSummary,
    TableSummaryCell,
    TableSummaryRow,
  } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  // import { puOrderPreDataDelete, puOrderPreDataPushAsn } from '/@/api/srm/asn/presh/puOrderPreData';
  import { useDrawer, useDrawerInner, BasicDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import { PageWrapper } from '/@/components/Page';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { NumEnum } from '/@/enums/defEnum';
  import { usePermission } from '/@/hooks/web/usePermission';
  import {
    jhPlanAreaListBhData,
    jhPlanAreaListXclData,
    jhPlanAreaSaveData,
    jhPlanAreaListData,
    jhPlanAreaListDataGroup,
    jhPlanAreaClearData,
  } from '/@/api/wms/jh/plan/jhPlanArea';
  import tzList from './tzList.vue';
  import invList from './invDrawerList.vue';
  import { jhPickDetailsbachSave } from '/@/api/wms/jh/pick/jhPickDetailsInv';
  import { companyTreeData } from '/@/api/sys/company';
  import { useUserStore } from '/@/store/modules/user';
  import InputFormView from './formView.vue';

  const { hasPermission } = usePermission();
  const userStore = useUserStore();

  const { t } = useI18n('rd.rd32.rdrecord32');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);

  const fqty = computed(() => {
    let sumfqty = 0;
    let sumfweight = 0;
    for (const record of getDataSource()) {
      const { fqty } = record;
      sumfqty += Number(fqty || 0);
      sumfweight += Number(record.fweight || 0);
    }
    return {
      fqty: sumfqty,
      fWeight: sumfweight.toFixed(2),
    };
  });

  const fqtyBh = computed(() => {
    let fqty = 0;
    let fWeight = 0;
    for (const record of getDataSource3()) {
      fqty += Number(record.fqty || 0);
      fWeight += Number(record.fweight || 0);
    }
    return {
      fWeight: fWeight.toFixed(2),
      fqty: fqty,
    };
  });

  const fweightBh = computed(() => {
    let sumfweight = 0;
    for (const record of getDataSource3()) {
      const { fweight } = record;
      sumfweight += Number(fweight || 0);
    }
    return sumfweight.toFixed(4);
  });

  const getTitle = {
    icon: meta.icon || 'i-ant-design:book-outlined',
    // value: meta.title || t('订单变更记录'),
  };

  const searchForm: FormProps = {
    baseColProps: { lg: 8, md: 8 },
    labelWidth: 90,
    // showResetButton:false,
    schemas: [
      {
        label: t('公司'),
        field: 'companyCode',
        fieldLabel: 'companyName',
        component: 'TreeSelect',
        componentProps: {
          api: companyTreeData,
          allowClear: true,
          immediate: true,
        },
      },
      {
        label: t('发货单号'),
        field: 'fbillno',
        component: 'Input',
      },
      {
        label: t('是否打包'),
        field: 'fifpack',
        component: 'Input',
      },
      {
        label: t('联系人'),
        field: 'fperson',
        component: 'Input',
      },

      {
        label: t('电话'),
        field: 'fphone',
        component: 'Input',
      },
      {
        label: t('地址'),
        field: 'faddress',
        component: 'Input',
      },
      {
        label: t('摘要'),
        field: 'fexplanation',
        component: 'Input',
      },
      {
        label: t('销售订单号'),
        field: 'forderno',
        component: 'Input',
      },
      {
        label: t('发货日期'),
        field: 'fdate',
        component: 'DatePicker',
        // component: 'RangePicker',
        componentProps: {
          format: 'YYYY-MM-DD',
          // showTime: { format: 'HH:mm' },
          showTime: false,
          valueFormat: 'YYYY-MM-DD',
        },
      },
      {
        label: t('收货单位'),
        field: 'fsuppliername',
        component: 'Input',
      },

      {
        label: t('紧急程度'),
        field: 'furgentlevel',
        component: 'Select',
        componentProps: {
          dictType: 'wms_jj_level',
          allowClear: true,
        },
      },
      {
        label: t('商品名称'),
        field: 'combinedProducts',
        component: 'Input',
      },
      {
        label: t('创建时间'),
        field: 'createDate',
        component: 'RangePicker',
      },
    ],
    fieldMapToTime: [
      ['dplanarrvdate', ['dplanarrvdate_gte', 'dplanarrvdate_lte']],
      ['parent.dorderdate', ['parent.dorderdate_gte', 'parent.dorderdate_lte']],
      ['createDate', ['createDate_gte', 'createDate_lte']],
    ],
  };

  const tableColumns: BasicColumn[] = [
    {
      title: t('子表ID'),
      dataIndex: 'cid',
      key: 'cid',
      sorter: true,
      width: 130,
      align: 'left',
      ifShow: false,
    },
    {
      title: t('打包'),
      dataIndex: 'fifpack',
      key: 'a.fifpack',
      sorter: true,
      width: 70,
      align: 'center',
    },
    {
      title: t('紧急程度'),
      dataIndex: 'furgentlevel',
      key: 'a.furgentlevel',
      sorter: true,
      width: 80,
      align: 'left',
      dictType: 'wms_jj_level',
    },
    {
      title: t('联系人'),
      dataIndex: 'fperson',
      key: 'a.fperson',
      sorter: true,
      width: 80,
      align: 'left',
    },
    {
      title: t('地址'),
      dataIndex: 'faddress',
      key: 'a.faddress',
      sorter: true,
      width: 160,
      align: 'left',
    },
    {
      title: t('商品名称'),
      dataIndex: 'combinedProducts',
      // key: 'a.combined_products',
      // sorter: true,
      width: 350,
      align: 'left',
      slot: 'combinedProducts',
    },
    {
      title: t('数量'),
      dataIndex: 'fqty',
      key: 'a.fqty',
      sorter: true,
      width: 60,
      align: 'right',
      showSummary: true,
      showTotalSummary: true,
    },
    {
      title: t('重量'),
      dataIndex: 'fweight',
      key: 'a.fweight',
      sorter: true,
      width: 60,
      align: 'right',
      showSummary: true,
      showTotalSummary: true,
    },
    {
      title: t('摘要'),
      dataIndex: 'fexplanation',
      key: 'a.fexplanation',
      sorter: true,
      width: 150,
      align: 'left',
    },
    {
      title: t('电话'),
      dataIndex: 'fphone',
      key: 'a.fphone',
      sorter: true,
      width: 100,
      align: 'left',
    },
    {
      title: t('销售订单号'),
      dataIndex: 'forderno',
      key: 'a.forderno',
      sorter: true,
      width: 110,
      align: 'left',
    },
    {
      title: t('发货单号'),
      dataIndex: 'fbillno',
      key: 'a.fbillno',
      sorter: true,
      width: 110,
      align: 'left',
      slot: 'firstColumn',
    },

    {
      title: t('创建时间'),
      dataIndex: 'createDate',
      key: 'a.create_date',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('发货日期'),
      dataIndex: 'fdate',
      key: 'a.fdate',
      sorter: true,
      width: 90,
      align: 'left',
      slot: 'fdate',
    },
    // {
    //   title: t('备货状态'),
    //   dataIndex: 'bhStatus',
    //   key: 'a.bhStatus',
    //   dictType: 'jh_bh_status',
    //   sorter: true,
    //   width: 80,
    //   align: 'center',
    // },

    // {
    //   title: t('存量状态'),
    //   dataIndex: 'bhStatus',
    //   key: 'a.bhStatus',
    //   // dictType: 'wms_bh_status',
    //   sorter: true,
    //   width: 80,
    //   align: 'center',
    // },
    {
      title: t('收货单位'),
      dataIndex: 'fsuppliername',
      key: 'a.fsuppliername',
      sorter: true,
      width: 200,
      align: 'left',
    },
  ];

  const table3Columns: BasicColumn[] = [
    {
      title: t('打包'),
      dataIndex: 'fifpack',
      key: 'a.fifpack',
      sorter: true,
      width: 70,
      align: 'center',
    },
    {
      title: t('摘要'),
      dataIndex: 'fexplanation',
      key: 'a.fexplanation',
      sorter: true,
      width: 150,
      align: 'left',
    },
    {
      title: t('联系人'),
      dataIndex: 'fperson',
      key: 'a.fperson',
      sorter: true,
      width: 80,
      align: 'left',
    },
    {
      title: t('商品名称'),
      dataIndex: 'combinedProducts',
      key: 'a.combined_products',
      sorter: true,
      width: 350,
      align: 'left',
      slot: 'combinedProducts',
    },
    {
      title: t('数量'),
      dataIndex: 'fqty',
      key: 'a.fqty',
      sorter: true,
      width: 60,
      align: 'right',
      showSummary: true,
      showTotalSummary: true,
    },
    {
      title: t('重量'),
      dataIndex: 'fweight',
      key: 'a.fweight',
      sorter: true,
      width: 60,
      align: 'right',
      showSummary: true,
      showTotalSummary: true,
    },
    {
      title: t('紧急程度'),
      dataIndex: 'furgentlevel',
      key: 'a.furgentlevel',
      sorter: true,
      width: 80,
      align: 'left',
      dictType: 'wms_jj_level',
    },
    {
      title: t('销售订单号'),
      dataIndex: 'forderno',
      key: 'a.forderno',
      sorter: true,
      width: 110,
      align: 'left',
    },
    {
      title: t('发货单号'),
      dataIndex: 'fbillno',
      key: 'a.fbillno',
      sorter: true,
      width: 110,
      align: 'left',
    },

    {
      title: t('电话'),
      dataIndex: 'fphone',
      key: 'a.fphone',
      sorter: true,
      width: 100,
      align: 'left',
    },
    {
      title: t('地址'),
      dataIndex: 'faddress',
      key: 'a.faddress',
      sorter: true,
      width: 160,
      align: 'left',
    },
    {
      title: t('备货状态'),
      dataIndex: 'bhStatus',
      key: 'a.bhStatus',
      dictType: 'jh_bh_status',
      sorter: true,
      width: 80,
      align: 'center',
    },

    // {
    //   title: t('存量状态'),
    //   dataIndex: 'bhStatus',
    //   key: 'a.bhStatus',
    //   // dictType: 'wms_bh_status',
    //   sorter: true,
    //   width: 80,
    //   align: 'center',
    // },
    {
      title: t('收货单位'),
      dataIndex: 'fsuppliername',
      key: 'a.fsuppliername',
      sorter: true,
      width: 200,
      align: 'left',
    },
  ];

  const actionColumn: BasicColumn = {
    width: 70,
    actions: (record: Recordable) => [
      {
        label: t('调整'),
        onClick: handleForm.bind(this, { groupFlag: record.groupFlag }),
        auth: 'jh:plan:jhPlanArea:edit',
      },
      // {
      //   label: t('检查'),
      //   onClick: handleUpdateXcl.bind(this, { groupFlag: record.groupFlag }),
      //   auth: 'jh:plan:jhPlanArea:edit',
      // },
      {
        title: t('添加备货区'),
        icon: 'i-fluent:add-12-filled',
        // onClick: handleAdd.bind(this, { groupFlag: record.groupFlag }),
        auth: 'jh:plan:jhPlanArea:edit',
        popConfirm: {
          title: t('是否确认添加备货区'),
          confirm: handleAdd.bind(this, { groupFlag: record.groupFlag }),
        },
      },
    ],
  };

  const [registerViewDrawer, { openDrawer: openViewDrawer }] = useDrawer();
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerDrawerInv, { openDrawer: openDrawerInv }] = useDrawer();

  const [
    registerTable,
    { reload, getForm, getDataSource, getSelectRows, setSelectedRowKeys, setProps },
  ] = useTable({
    api: jhPlanAreaListBhData,
    beforeFetch: (params) => {
      // params.companyCode = companyData.value.code || '-1';
      return params;
    },
    columns: tableColumns,
    actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    showSearchForm: false,
    canResize: true,
    tableSetting: {
      redo: false,
    },
    tableSettingStoreKey: 'registerTable',
    // maxHeight: 250,
    // rowSelection: {
    //   type: 'checkbox',
    // },
    immediate: false,
    ellipsis: false,
    showCustomSummary: true,
    showTotalCustomSummary: true,
  });

  const actionColumn3: BasicColumn = {
    width: 80,
    actions: (record: Recordable) => [
      {
        title: t('删除'),
        icon: 'i-ant-design:delete-outlined',
        color: 'error',
        popConfirm: {
          title: t('是否确认删除'),
          confirm: handleDelete.bind(this, { ids: record.id }),
        },
        auth: 'jh:plan:jhPlanArea:edit',
      },
    ],
  };
  const [
    registerTable3,
    {
      reload: reload3,
      setTableData: setTableData3,
      getDataSource: getDataSource3,
      getSelectRows: getSelectRows3,
      setProps: setProps3,
    },
  ] = useTable({
    api: jhPlanAreaListDataGroup,
    beforeFetch: (params) => {
      //params.companyCode = companyData.value.code || '-1';
      return params;
    },
    columns: table3Columns,
    // actionColumn: actionColumn3,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: false,
    canResize: true, //表格是否flex布局
    // isCanResizeParent: true,
    // maxHeight: 600,

    immediate: false, //懒加载
    tableSetting: {
      redo: false,
      size: false,
    },
    tableSettingStoreKey: 'registerTable3',
    rowSelection: {
      type: 'checkbox',
    },
    showCustomSummary: true,
    showTotalCustomSummary: true,
  });

  const [registerForm, { validate }] = useForm({
    labelWidth: 100,
    schemas: [
      {
        label: t('拣货方式'),
        field: 'type',
        component: 'Select',
        defaultValue: '1',
        componentProps: {
          dictType: 'jh_type',
          // allowClear: true,
        },
        required: true,
      },
      {
        label: t('是否分单'),
        field: 'splitOrder',
        component: 'Select',
        defaultValue: '0',
        componentProps: {
          dictType: 'sys_yes_no',
          // allowClear: true,
        },
        required: true,
      },
    ],
    baseColProps: { lg: 24, md: 24 },
  });
  const [registerModal, { openModal, closeModal, setModalProps }] = useModal();

  async function handleQr() {
    try {
      let dataValidate = await validate();
      setModalProps({ confirmLoading: true });
      const jhPlanAreaList = getSelectRows3();
      const params: any = {
        isNewRecord: true,
      };
      const ids = jhPlanAreaList.map((item) => item.id).join(',');
      const data: any = {
        ...dataValidate,
        selIds: ids,
      };
      const res = await jhPickDetailsbachSave(params, data);
      showMessage(res.message);
      reload();
      reload3();
      closeModal();
      // setTableData3([]);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  async function handleUpdateXcl(record: Recordable) {
    const groupIds = record.groupFlag;
    const res = await jhPlanAreaListXclData({
      groupFlag: groupIds,
    });
    showMessage(res.message);
    reload();
  }
  const isClearing = ref(false);
  async function handlegx() {
    if (getSelectRows3().length <= 0) {
      showMessage('请先勾选后清除');
      return;
    }
    if (isClearing.value) {
      showMessage('正在处理,请稍后...');
      return;
    }
    try {
      isClearing.value = true;
      const data: any = {};
      data.ids = getSelectRows3()
        .map((item) => item.id)
        .join(',');
      const res = await jhPlanAreaClearData(data);
      showMessage(res.message);
      reload();
      reload3();
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      isClearing.value = false;
    }
  }
  function handlecombinedProducts(value) {
    // 检查 value 是否为空或未定义
    if (!value || typeof value !== 'string') {
      return value || '';
    }
    let newStr = value.replace(/##/g, '<br>'); // 替换所有'##'为'<br>'
    return newStr;
  }

  async function handleDelete(record: Recordable) {
    // console.log('record', record.ids);
    const res = await jhPlanAreaClearData({ ids: record.id });
    await reload();
    await reload3();
    await showMessage(res.message);
  }

  const isBatch = ref(false);
  async function handlebr() {
    if (isBatch.value) {
      showMessage('正在处理,请稍后...');
      return;
    }
    try {
      isBatch.value = true;
      const res = await jhPlanAreaClearData();
      showMessage(res.message);
      reload();
      reload3();
      setTableData3([]);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      isBatch.value = false;
    }
  }

  function handleViewForm(record: Recordable) {
    openViewDrawer(true, record);
  }

  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  const isAdding = ref(false);
  async function handleAdd(record: Recordable) {
    if (isAdding.value) {
      showMessage('正在处理,请稍后...');
      return;
    }
    try {
      isAdding.value = true;
      const res = await jhPlanAreaSaveData({
        groupFlag: record.groupFlag,
      });
      showMessage(res.message);
      reload();
      reload3();
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      isAdding.value = false;
    }

  }
  // 鼠标行点击事件，获取上表数据

  onMounted(async () => {
    setProps();
    setProps3();
    await reload();
    await reload3();
    await getForm().setFieldsValue({
      companyCode: userStore.getProjecte.code,
    });
    // setTableData3([]);
  });

  async function rowChange({ column, value, record }) {
    // let { editValueRefs: { ntotalnum } } = record;
    // if (value > record.nversion) {
    //   showMessage('本次送货数不能超过剩余数！');
    //   ntotalnum.value = record.nversion
    // }
    let {
      editValueRefs: { selQty },
    } = record;
    selQty.value = value.toFixed(NumEnum.scaleSelQty);
  }

  // 生成拣货单
  async function handleCreateJhBill() {
    if (getSelectRows3().length == 0) {
      showMessage('请先勾选后生成拣货单');
      return;
    }
    openModal(true, {});
  }

  async function handleInventory(record: Recordable) {
    openDrawerInv(true, record);
  }
</script>
<style scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }

  :deep(.edit-cell-align-center) {
    width: 100% !important;
  }

  .title1 {
    width: 100%;
    min-height: calc(100vh - 120px);
    display: flex;
    flex-direction: column;
    /* background: #ffffff;
    padding: 20px;
    display: flex;
    justify-content: center;
    align-items: center; */
  }
</style>
